import { defineComponent, reactive, ref, onMounted } from 'vue'
import {
  ElCard,
  ElFormItem,
  ElInput,
  ElSelect,
  ElOption,
  ElSpace,
  ElLink,
  ElMessageBox,
  ElMessage,
  ElButton
} from 'element-plus'
import { useStore } from 'vuex'
import type { FormValuesType } from './typings'
import type { TableColumnProps, ProSaasTableExposeType } from '~/components/ProSaasTable/typings'
import ProSaasTable from '~/components/ProSaasTable'
import useVuexGetters from '~/hooks/useVuexGetters'
import AliIcon from '~/components/AliIocn'
import styles from '../../index.module.scss'
import InfoView from './info'

export default defineComponent(function ManholeAlarm() {
  const store = useStore()
  const proSaasTableRef = ref<ProSaasTableExposeType>()
  const formValues = reactive<FormValuesType>({})
  const userState = useVuexGetters('user', ['permission'])
  const manholeState = useVuexGetters('manhole', ['manholeModelOpt'])
  const assetWorkAreaState = useVuexGetters('assetWorkArea', ['workAreaSelectList'])
  const state = reactive<any>({
    infoVisible: false,
    record: {}
  })
  const columns: TableColumnProps<FormValuesType>[] = [
    {
      label: '警报名称',
      prop: 'alarmName',
      minWidth: 160,
      fixed: 'left',
      unFixed: true,
      showOverflowTooltip: true,
      sortable: true,
      disabled: true
    },
    {
      label: '所属工区',
      prop: 'workAreaName',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '设备名称',
      prop: 'deviceName',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '设备型号',
      prop: 'modelName',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '警报地址',
      prop: 'alarmAddress',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '警报状态',
      prop: 'alarmState',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true,
      render: (_, value) => <>{value === 1 ? '报警' : '恢复'}</>
    },
    {
      label: '警报时间',
      prop: 'reportTime',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '恢复时间',
      prop: 'recoverTime',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '更新日期',
      prop: 'updateTime',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '工单状态',
      prop: 'orderState',
      minWidth: 160,
      showOverflowTooltip: true,
      sortable: true
    },
    {
      label: '操作',
      prop: 'options',
      minWidth: 260,
      align: 'center',
      fixed: 'right',
      unFixed: true,
      disabled: true,
      render: ({ row }) => (
        <ElSpace>
          {userState.permission.value.has('monitor_manhole_alarm_push') && (
            <ElLink type="primary" onClick={() => ignore(row)}>
              <AliIcon type="icon-hulve1" />
              &nbsp; 忽略&nbsp;&nbsp;
            </ElLink>
          )}
          <ElLink type="primary" onClick={() => infoOpen(row)}>
            <AliIcon type="icon-chakan" />
            &nbsp; 详情&nbsp;&nbsp;
          </ElLink>
          {userState.permission.value.has('monitor_manhole_alarm_push') &&
            row.orderState === '未推送' && (
              <ElLink type="primary" onClick={() => pushOrder(row)}>
                <AliIcon type="icon-yichu1" />
                &nbsp; 推送工单
              </ElLink>
            )}
        </ElSpace>
      )
    }
  ]
  //  按回车搜索列表
  const handleKeyDownEnterSubmitForm = (evt: Event | KeyboardEvent) => {
    if ((evt as KeyboardEvent).key === 'Enter') proSaasTableRef.value!?.toSearch()
  }
  //  清空搜索
  const clearSearchTable = async () => {
    setTimeout(() => {
      proSaasTableRef.value!?.toSearch()
    }, 100)
  }
  //  忽略
  const ignore = (row: FormValuesType) => {
    ignoreAjax(row.id, true)
  }
  //  批量忽略
  const allIgnore = () => {
    const ids = proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    if (!ids) {
      ElMessage({ type: 'warning', message: '请勾选数据' })
      return
    }
    ignoreAjax(ids, false)
  }
  //  忽略请求
  const ignoreAjax = async (ids: any, value: boolean) => {
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {value && <p class="delete-title">确认忽略警报信息?</p>}
          {!value && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认忽略选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认忽略选中数据？'}
            </p>
          )}
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    }).then(async () => {
      const { code } = await store.dispatch('manholes/ManholeAlarmIgnoreAlarmGet', { ids })
      if (code === 200) {
        proSaasTableRef.value!?.clearSelection?.()
        proSaasTableRef.value!?.toSearch()
        ElMessage({ type: 'success', message: '操作成功' })
      }
    })
  }
  //  推送工单
  const pushOrder = (row: FormValuesType) => {
    orderAjax(row.id, true)
  }
  //  批量推送工单
  const allPushOrder = () => {
    const ids = proSaasTableRef.value!.selecteds?.map?.((item) => item!?.id)?.join(',')
    if (!ids) {
      ElMessage({ type: 'warning', message: '请勾选数据' })
      return
    }
    orderAjax(ids, false)
  }
  //  推送工单请求
  const orderAjax = async (ids: any, value: boolean) => {
    ElMessageBox({
      title: '确认提示',
      message: (
        <section class={styles['delete-confirm-box']}>
          {value && <p class="delete-title">确认推送工单?</p>}
          {!value && (
            <p class="delete-title">
              {proSaasTableRef.value!.selecteds?.length > 1
                ? `确认推送选中的${proSaasTableRef.value!.selecteds?.length}条数据?`
                : '确认推送选中数据？'}
            </p>
          )}
          {/* <p class="delete-content">推送后不可恢复，是否确认推送。</p> */}
        </section>
      ),
      showCancelButton: true,
      confirmButtonText: '确认',
      cancelButtonText: '取消',
      closeOnClickModal: false, // 点遮罩层不关弹窗
      draggable: true // 可拖拽
    }).then(async () => {
      const { code } = await store.dispatch('manholes/ManholeAlarmPushOrderGet', { ids })
      if (code === 200) {
        proSaasTableRef.value!?.clearSelection?.()
        proSaasTableRef.value!?.toSearch()
        ElMessage({ type: 'success', message: '操作成功' })
      }
    })
  }
  //  详情
  const infoOpen = (row?: FormValuesType) => {
    state.infoVisible = !state.infoVisible
    state.record = row || {}
  }
  onMounted(async () => {
    //  井盖型号
    await store.dispatch('manhole/ManholeModelGet')
    // 所属区域
    await store.dispatch('assetWorkArea/GetWorkAreaSelectListByUser')
  })
  return () => {
    if (state.infoVisible) {
      return <InfoView record={state.record} cancel={() => infoOpen()} />
    }
    return (
      <ElCard>
        <ProSaasTable
          tableId="ManholeAlarm"
          ref={proSaasTableRef}
          columns={columns}
          hasSelection
          dispatchType="manholes/ManholeAlarmListGet"
          searchFormProps={{
            model: formValues
          }}
          headerTitle={
            <>
              {userState.permission.value.has('monitor_manhole_alarm_push') && (
                <ElButton type="primary" onClick={allPushOrder}>
                  <AliIcon type="icon-yichu1" />
                  &nbsp; 推送工单
                </ElButton>
              )}
              {userState.permission.value.has('monitor_manhole_alarm_push') && (
                <ElButton type="danger" onClick={allIgnore}>
                  <AliIcon type="icon-hulve1" />
                  &nbsp; 批量忽略
                </ElButton>
              )}
            </>
          }
          searchformResponsiveCol={[
            <ElFormItem key="keyWord" prop="keyWord" label="">
              <ElInput
                v-model={formValues.keyWord}
                placeholder="设备名称或设备编号"
                clearable
                onKeydown={handleKeyDownEnterSubmitForm}
                onClear={clearSearchTable}
              />
            </ElFormItem>,
            <ElFormItem key="modelId" prop="modelId">
              <ElSelect
                v-model={formValues.modelId}
                placeholder="型号"
                clearable
                onChange={clearSearchTable}
              >
                {manholeState.manholeModelOpt.value?.map((item: any) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                ))}
              </ElSelect>
            </ElFormItem>,
            <ElFormItem key="workAreaId" prop="workAreaId">
              <ElSelect
                v-model={formValues.workAreaId}
                placeholder="所属区域"
                clearable
                onChange={clearSearchTable}
              >
                {assetWorkAreaState.workAreaSelectList?.value?.map((item: any) => (
                  <ElOption key={item?.id} label={item?.name} value={item?.id!} />
                ))}
              </ElSelect>
            </ElFormItem>
          ]}
        />
      </ElCard>
    )
  }
})
